import {
  ADD_TODO,
  DELETE_TODO,
  EDIT_TODO,
  COMPLETE_TODO,
  COMPLETE_ALL_TODOS,
  CLEAR_COMPLETED,
  SET_VISIBILITY_FILTER
} from '../constants/ActionTypes'

import {
  SHOW_ALL
} from '../constants/TodoFilters'

const initialState = {
  filter: SHOW_ALL,
  todos: [
    {
      text: 'Use Redux',
      completed: false,
      id: 0
    }
  ]
}

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return {
        filter: state.filter,
        todos: [
          ...state.todos,
          {
            id: state.todos.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
            completed: false,
            text: action.text
          }
        ]
      }

    case DELETE_TODO:
      return {
        filter: state.filter,
        todos:
          state.todos.filter(todo =>
            todo.id !== action.id
          )
      }

    case EDIT_TODO:
      return {
        filter: state.filter,
        todos: state.todos.map(todo =>
          todo.id === action.id ?
            { ...todo, text: action.text } :
            todo
        )
      }

    case COMPLETE_TODO:
      return {
        filter: state.filter,
        todos: state.todos.map(todo =>
          todo.id === action.id ?
            { ...todo, completed: !todo.completed } :
            todo
        )
      }

    case COMPLETE_ALL_TODOS:
      const areAllMarked = state.todos.every(todo => todo.completed)
      return {
        filter: state.filter,
        todos: state.todos.map(todo => ({
          ...todo,
          completed: !areAllMarked
        }))
      }

    case CLEAR_COMPLETED:
      return {
        filter: state.filter,
        todos: state.todos.filter(todo => todo.completed === false)
      }

    case SET_VISIBILITY_FILTER:
      return {
        filter: action.filter,
        todos: state.todos
      }

    default:
      return state
  }
}